import "./index.css";

document.addEventListener("DOMContentLoaded", () => {
  const appElement = document.getElementById("app")!;
  const link = "https://github.com/bikathi/ts-chrome-ext-starter";
  let countSync = 0;

  // Create the main element
  const mainElement = document.createElement("main");

  // Create the title element
  const h3Element = document.createElement("h3");
  h3Element.textContent = "SidePanel Page";

  // Create the counter element
  const h4Element = document.createElement("h4");
  h4Element.textContent = `Count from Popup: `;
  const countSyncElement = document.createElement("span");
  countSyncElement.textContent = "0";
  h4Element.appendChild(countSyncElement);

  // Create the link element
  const aElement = document.createElement("a");
  aElement.href = link;
  aElement.target = "_blank";
  aElement.textContent = "executed from starter template";

  // Append all elements to the main element
  mainElement.appendChild(h3Element);
  mainElement.appendChild(h4Element);
  mainElement.appendChild(aElement);

  // Append the main element to the page
  appElement.appendChild(mainElement);

  // Get the count value from Chrome storage
  chrome.storage.sync.get(["count"], (result) => {
    countSync = result.count || 0;
    countSyncElement.textContent = `${countSync}`;
  });

  // Listen for messages from the Popup
  chrome.runtime.onMessage.addListener((request) => {
    if (request.type === "COUNT") {
      countSync = request.count || 0;
      countSyncElement.textContent = `${countSync}`;
    }
  });
});
